package cn.funeralobjects.minecraft.service.impl;

import cn.funeralobjects.minecraft.handler.PlayerLoginHandler;
import cn.funeralobjects.minecraft.service.MinecraftAuthService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author FuneralObjects
 * Create date: 2020/11/15 9:29 AM
 */
@Service
public class MinecraftAuthServiceImpl implements MinecraftAuthService {

    private final AtomicReference<List<PlayerLoginHandler>> cacheList = new AtomicReference<>();

    @PostConstruct
    private void init() {
        cacheList.set(new ArrayList<>());
    }


    @Override
    public Flux<PlayerLoginHandler> getAllHandlers() {
        return Flux.fromIterable(cacheList.get() == null ? Collections.emptyList() : cacheList.get());
    }


    @Override
    public Mono<Void> insert(Integer index, PlayerLoginHandler loginHandler) {
        return Mono.just(index)
                .flatMap(i -> {
                    cacheList.get().add(i, loginHandler);
                    return Mono.empty();
                });

    }

    @Override
    public Mono<PlayerLoginHandler> remove(Integer index) {
        return Mono.just(index)
                .map(i -> cacheList.get().remove(i.intValue()));
    }

    @Override
    public Mono<Void> replace(Integer index, PlayerLoginHandler loginHandler) {
        return Mono.just(index)
                .flatMap(i -> {
                    cacheList.get().set(i, loginHandler);
                    return Mono.empty();
                });
    }

}
